package yunjiao.javatutorials.lang.concurrent;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程工厂和拒绝策略
 *
 * @author yangyunjiao
 */
public class AdvancedThreadPoolExample {
    static class CustomThreadFactory implements ThreadFactory {
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        CustomThreadFactory(String poolName) {
            namePrefix = poolName + "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
            t.setDaemon(false);
            t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

    static class CustomRejectionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.println("任务被拒绝，当前队列大小: " + executor.getQueue().size());
            // 可以记录日志、保存到数据库或发送告警
            if (!executor.isShutdown()) {
                r.run(); // 在调用者线程中执行
            }
        }
    }

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, 4, 60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(5),
                new CustomThreadFactory("CustomPool"),
                new CustomRejectionHandler()
        );

        // 允许核心线程超时
        executor.allowCoreThreadTimeOut(true);

        // 提交任务
        for (int i = 1; i <= 10; i++) {
            final int taskId = i;
            executor.submit(() -> {
                System.out.println(Thread.currentThread().getName() +
                        " 执行任务 " + taskId);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        // 动态调整线程池参数
        adjustThreadPoolParameters(executor);

        executor.shutdown();
    }

    private static void adjustThreadPoolParameters(ThreadPoolExecutor executor) {
        // 动态调整核心线程数
        executor.setCorePoolSize(3);
        executor.setMaximumPoolSize(6);

        System.out.println("调整后核心线程数: " + executor.getCorePoolSize());
        System.out.println("调整后最大线程数: " + executor.getMaximumPoolSize());
    }
}
